/**
 * 用户ID相关的hooks
 */

import { useState, useEffect } from 'react';
import { generateAnonymousUserId } from '@/services/AnonymousUser/api';

/**
 * 用户身份信息
 */
export interface UserIdentity {
  userId: string;
  isLoggedIn: boolean;
  isTempUser: boolean;
  username?: string;
  avatar?: string;
}

// 🔒 全局标志：防止重复调用后端生成ID
let isGeneratingId = false;
let generatingPromise: Promise<string> | null = null;

/**
 * 从后端获取或创建匿名用户ID
 * 注意：匿名用户ID本质上也是userId，只是15位长度
 */
const getAnonymousUserId = async (): Promise<string> => {
  let userId = localStorage.getItem('userId');
  
  // 🔥 强制清理：检测到任何错误值都直接删除
  if (userId) {
    const isInvalid = 
      userId === '[object Object]' ||
      userId === 'undefined' ||
      userId === 'null' ||
      userId.includes('object') ||
      userId.includes('Object') ||
      userId.length !== 15 ||
      !/^\d{15}$/.test(userId);
    
    if (isInvalid) {
      console.warn('🧹 [清理] 检测到无效的userId，强制清除:', userId);
      localStorage.removeItem('userId');
      userId = null;
    } else {
      console.log('✅ [匿名用户] 使用已存在的有效userId:', userId);
      return userId;
    }
  }

  // 🔒 防止重复调用：如果正在生成，等待已有的Promise
  if (isGeneratingId && generatingPromise) {
    console.log('⏳ [等待] 正在生成中，等待已有的请求完成...');
    return generatingPromise;
  }

  // 标记正在生成
  isGeneratingId = true;
  
  // 创建生成Promise
  generatingPromise = (async () => {
    let userId: string | null = null;
    try {
      // 调用后端API生成匿名用户ID
      const response = await generateAnonymousUserId();
      console.log('📡 [调试] 后端完整响应:', response);
      
      // 后端有全局响应包装，格式为 {code: 200, data: xxx, message: xxx, success: true}
      let anonymousUserId;
      
      if (typeof response === 'object' && response !== null) {
        if ('data' in response && response.data !== undefined) {
          anonymousUserId = response.data;
          console.log('📦 [解析] 从response.data提取ID:', anonymousUserId);
        } else {
          anonymousUserId = response;
        }
      } else {
        anonymousUserId = response;
      }
      
      console.log('🔍 [验证] 提取的匿名用户ID:', anonymousUserId, '类型:', typeof anonymousUserId);
      
      if (anonymousUserId !== null && anonymousUserId !== undefined) {
        userId = String(anonymousUserId);
        
        // 验证是否为有效的15位数字
        if (userId.length === 15 && /^\d{15}$/.test(userId)) {
          // 统一存储为userId，不区分临时
          localStorage.setItem('userId', userId);
          console.log('✅ [成功] 从后端生成匿名用户ID并保存为userId:', userId);
          return userId;
        } else {
          console.error('❌ [错误] 后端返回的ID格式不正确，长度:', userId.length, '值:', userId);
        }
      }
    } catch (error) {
      console.error('❌ [错误] 从后端生成匿名用户ID失败:', error);
    } finally {
      // 重置标志位
      isGeneratingId = false;
      generatingPromise = null;
    }

    // 如果后端调用失败，使用前端生成（备用方案）
    userId = generateAnonymousUserIdFallback();
    localStorage.setItem('userId', userId);
    console.warn('⚠️ [备用] 后端生成失败，使用前端生成:', userId);
    return userId;
  })();

  return generatingPromise;
};

/**
 * 前端生成匿名用户ID（备用方案）
 * 格式：YYMMDDHHMMSS + 3位随机数 = 15位
 */
const generateAnonymousUserIdFallback = (): string => {
  const now = new Date();
  const year = (now.getFullYear() % 100).toString().padStart(2, '0');
  const month = (now.getMonth() + 1).toString().padStart(2, '0');
  const day = now.getDate().toString().padStart(2, '0');
  const hour = now.getHours().toString().padStart(2, '0');
  const minute = now.getMinutes().toString().padStart(2, '0');
  const second = now.getSeconds().toString().padStart(2, '0');
  const random = Math.floor(Math.random() * 900 + 100).toString();
  return `${year}${month}${day}${hour}${minute}${second}${random}`;
};

/**
 * 检查是否为临时用户ID（15位数字）
 */
const isTempUserId = (userId: string): boolean => {
  return userId.length === 15 && /^\d{15}$/.test(userId);
};

/**
 * 获取当前用户ID
 * 登录用户：返回user表的ID（如1,2,3...）
 * 匿名用户：返回anonymous_user表的ID（15位）
 * 统一作为userId使用，后端根据长度判断查询哪个表
 */
export const useUserId = (): string => {
  const [userId, setUserId] = useState<string>('');

  useEffect(() => {
    const initUserId = async () => {
      try {
        // 1. 优先获取已登录用户信息
        const userInfo = localStorage.getItem('userInfo');
        if (userInfo) {
          const user = JSON.parse(userInfo);
          if (user.id) {
            const loginUserId = user.id.toString();
            // 保存到userId（统一字段）
            localStorage.setItem('userId', loginUserId);
            setUserId(loginUserId);
            console.log('✅ [登录用户] userId:', loginUserId);
            return;
          }
        }
      } catch (error) {
        console.warn('获取登录用户信息失败:', error);
      }
      
      // 2. 未登录，检查是否已有匿名userId
      let anonymousId = localStorage.getItem('userId');
      
      // 清理旧的tempUserId
      const oldTempId = localStorage.getItem('tempUserId');
      if (oldTempId && !anonymousId) {
        console.log('🔄 [迁移] 将tempUserId迁移到userId');
        anonymousId = oldTempId;
        localStorage.removeItem('tempUserId');
      }
      
      // 验证匿名userId是否有效
      if (anonymousId && anonymousId.length === 15 && /^\d{15}$/.test(anonymousId)) {
        setUserId(anonymousId);
        console.log('✅ [匿名用户] 使用已存在的userId:', anonymousId);
        return;
      }
      
      // 3. 从后端获取新的匿名userId
      const newAnonymousId = await getAnonymousUserId();
      setUserId(newAnonymousId);
    };

    initUserId();
  }, []);

  return userId;
};

/**
 * 获取用户身份信息
 */
export const useUserIdentity = (): UserIdentity => {
  const [identity, setIdentity] = useState<UserIdentity>({
    userId: '',
    isLoggedIn: false,
    isTempUser: true,
  });

  useEffect(() => {
    const initIdentity = async () => {
      try {
        // 1. 检查是否为登录用户
        const userInfo = localStorage.getItem('userInfo');
        if (userInfo) {
          const user = JSON.parse(userInfo);
          if (user.id) {
            const loginUserId = user.id.toString();
            localStorage.setItem('userId', loginUserId);
            setIdentity({
              userId: loginUserId,
              isLoggedIn: true,
              isTempUser: false,
              username: user.username,
              avatar: user.avatar,
            });
            console.log('✅ [登录用户] 身份信息已加载');
            return;
          }
        }
      } catch (error) {
        console.warn('获取用户信息失败:', error);
      }
      
      // 2. 未登录，获取或生成匿名userId
      const anonymousId = await getAnonymousUserId();
      setIdentity({
        userId: anonymousId,
        isLoggedIn: false,
        isTempUser: true,  // 15位ID表示匿名用户
      });
      console.log('✅ [匿名用户] 身份信息已加载');
    };

    initIdentity();
  }, []);

  return identity;
};

/**
 * 获取当前用户ID，未登录则使用默认ID
 * @param defaultId 默认ID，默认为'1'
 * @deprecated 建议使用useUserId，已包含临时ID逻辑
 */
export const useUserIdOrDefault = (defaultId: string = '1'): string => {
  const userId = useUserId();
  return userId || defaultId;
};

